/**
 * @Author Luming
 * @Date 2024/4/28 13:18
 * @Description:
 */
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/ChatServlet")
public class ChatServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        String username = request.getParameter("username");
        String message = request.getParameter("message");

        if (username != null && message != null) {
            // 获取当前会话的session
            HttpSession session = request.getSession(true);

            // 获取当前聊天消息列表
            List<String> messages = (List<String>) getServletContext().getAttribute("messages");
            if (messages == null) {
                messages = new ArrayList<>();
                getServletContext().setAttribute("messages", messages);
            }
            // 添加新消息
            messages.add(username + ": " + message);

            // 将用户名保存到session中
            session.setAttribute("username", username);
        }

        response.sendRedirect("chat.jsp");
    }
}
